from rest_framework import serializers

from dvadmin.system.models import FileList
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin.utils.json_response import DetailResponse,EditorFIleResponse
from rest_framework.decorators import action


class FileSerializer(CustomModelSerializer):
    url = serializers.SerializerMethodField(read_only=True)

    def get_url(self, instance):
        return '/media/' + str(instance.url)

    class Meta:
        model = FileList
        fields = "__all__"

    def create(self, validated_data):
        validated_data['name'] = str(self.initial_data.get('file'))
        validated_data['url'] = self.initial_data.get('file')
        return super().create(validated_data)

class FileViewSet(CustomModelViewSet):
    """
    文件管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = FileList.objects.all()
    serializer_class = FileSerializer
    filter_fields = ['name', ]
    permission_classes = []


    @action(methods=['POST'], detail=True, permission_classes=[])
    def onefileupdate(self, request, *args, **kwargs):
        """
        用户单个文件上传
        """
        serializer = self.get_serializer(data=request.data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        data = [{'success': True,"url": serializer.data['url']}]
        return EditorFIleResponse(data=data, msg="新增成功")

    @action(methods=['POST'], detail=True, permission_classes=[])
    def fileupdate(self, request, *args, **kwargs):
        """
        用户编辑器文件以及图片上传
        """
        serializer = self.get_serializer(data=request.data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        data = {
             "succMap": {
                serializer.data['name']: serializer.data['url'],
               }
             }
        return EditorFIleResponse(data=data, msg="新增成功")

    @action(methods=['POST'], detail=True, permission_classes=[])
    def pasteupdate(self, request, *args, **kwargs):
        """
        用户编辑器文件以及图片上传链接图片地址上传
        """
        serializer = self.get_serializer(data=request.data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        print(serializer.data)
        data = {
               'originalURL': '',
               'url':  serializer.data['url'],
             }

        return EditorFIleResponse(data=data, msg="新增成功")